import gradio as gr
import os
import sys
from pathlib import Path
from utils import ArgumentParser, ConfigLoader, LOG
from model import OpenAIModel
from translator import PDFTranslator

# 添加当前脚本所在目录到系统路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 加载配置
config_loader = ConfigLoader("config.yaml")
config = config_loader.load_config()

# 初始化模型
model_name = config['OpenAIModel']['model']
api_key = config["OpenAIModel"]["api_key"]
model = OpenAIModel(model=model_name, api_key=api_key)

translator = PDFTranslator(model)

def translate_pdf_file(pdf_file, target_language, pages, loader=gr.HTML()):
    # 检查 pdf_file 是否为 None
    if pdf_file is None:
        LOG.error("上传的 PDF 文件为空")
        return None, None, "请上传一个有效的 PDF 文件"

    # progress(0.1, desc="检查文件路径")
    # 确保 pdf_file 是文件路径
    if hasattr(pdf_file, 'name'):
        file_path = pdf_file.name
    elif isinstance(pdf_file, str):  # 如果是字符串路径
        file_path = pdf_file
    else:
        raise ValueError("Unsupported file type: pdf_file must be a file object or string path")

    try:
        # 如果 pdf_file 是文件对象，保存其内容到临时文件
        if hasattr(pdf_file, 'read'):
            temp_file_path = file_path + "_temp"
            with open(temp_file_path, "wb") as f:
                f.write(pdf_file.read())
            file_path = temp_file_path
            # 更新进度
            # progress(0.1, desc="保存临时文件")

        # progress(0.4, desc="开始翻译")
        # 调用翻译方法
        translated_file_path, error_message = translator.translate_pdf(file_path, "pdf", target_language, pages=pages)
        # progress(0.8, desc="翻译完成")

        # 检查 translated_file_path 是否为 None
        if translated_file_path is None:
            LOG.error(f"翻译失败: {error_message}")
            return None, None, error_message

        # 打印日志检查路径
        print(f"翻译后的文件路径: {translated_file_path}")
        if not os.path.exists(translated_file_path):
            LOG.error(f"翻译后的文件不存在: {translated_file_path}")
            return None, None, "翻译后的文件不存在"

        # 删除临时文件（如果存在）
        if file_path.endswith("_temp"):
            os.remove(file_path)
            # progress(0.9, desc="删除临时文件")

        # 生成 PDF 预览的 HTML 代码
        pdf_preview = f'<embed src="{translated_file_path}" type="application/pdf" width="100%" height="600px" />'
        # 更新进度
        # progress(1, desc="翻译任务完成")
        return translated_file_path, pdf_preview, ""

    except Exception as e:
        LOG.error(f"翻译失败: {e}")
        return None, None, f"翻译失败: {e}"

def handle_translation(pdf_file, target_language, pages, loader=gr.HTML()):
    # 禁用翻译按钮
    yield None, None, gr.update(value="", visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(interactive=False), '''
     <style>
    /* 定义加载动画容器样式 */
    .loading-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100px;
        transition: opacity 0.3s ease-in-out; /* 添加过渡效果 */
    }

    /* 定义加载动画样式 */
    .custom-loader {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        border: 6px solid rgba(0, 0, 0, 0.1);
        border-top-color: #2196F3;
        animation: spin 1s ease-in-out infinite;
    }

    /* 定义旋转动画 */
    @keyframes spin {
        to {
            transform: rotate(360deg);
        }
    }
    </style>
    <div class="loading-container">
        <div class="custom-loader"></div>
    </div>
    '''

    translated_file_path, pdf_preview, error_message = translate_pdf_file(pdf_file, target_language, pages, loader)

    if error_message:
        yield None, None, gr.update(value=error_message, visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(interactive=True), ''
    else:
        yield translated_file_path, pdf_preview, gr.update(value="", visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(interactive=True), ''

def clear_error_display():
    return gr.update(value="", visible=False)

with gr.Blocks() as demo:
    gr.Markdown("# PDF Translator")
    with gr.Row():
        pdf_file = gr.File(
            label="请上传 PDF 文件", 
            file_types=[".pdf"], 
            type="filepath"
        )
        lang_choice = gr.Dropdown(
            label="选择翻译语言",
            choices=["中文", "日文", "韩文", "俄罗斯语", "西班牙语", "葡萄牙语"],
            value="中文"
        )
        pages_input = gr.Number(
            label="翻译页数",
            minimum=1,
            step=1,
            value=1
        )

    # progress_bar = gr.Progress()
    loader = gr.HTML(value='')
    translate_btn = gr.Button("翻译")
    output_file = gr.File(label="翻译后的文件", visible=False)
    pdf_preview = gr.HTML(label="PDF 预览", visible=False)
    error_display = gr.Textbox(label="错误信息", visible=False)

    # 监听文件上传事件，清除错误信息
    pdf_file.change(fn=clear_error_display, inputs=[], outputs=[error_display])

    translate_btn.click(
        fn=handle_translation,
        inputs=[pdf_file, lang_choice, pages_input],
        outputs=[output_file, pdf_preview, error_display, output_file, pdf_preview, translate_btn, loader]
    )

if __name__ == "__main__":
    demo.launch(debug=True, share=True, server_port=7860)